﻿using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Text;

namespace Chat
{
    class Protocol
    {
        public string Method;
        public string[] Header;
        public JToken Body;
        public Protocol(string str)
        {
            string[] h = str[..str.IndexOf("\n\n")].Split('\n');
            Method = h[0];
            Header = h[1..];
            try
            {
                Body = JToken.Parse(str[(str.IndexOf("\n\n") + 2)..]);
            }
            catch (Exception)
            {
                Body = null;
            }
        }
        public Protocol(string method, string[] header, JToken body)
        {
            Method = method;
            Header = header;
            Body = body;
        }
        public override string ToString()
        {
            string ret = Method + '\n';
            foreach (var i in Header)
            {
                ret += i + '\n';
            }
            ret += "\n" + Body.ToString();
            return ret;
        }
        public static string sha512Encode(string source)
        {
            string result = "";
            byte[] buffer = Encoding.UTF8.GetBytes(source);  //UTF-8 encode

            SHA512CryptoServiceProvider SHA512 = new SHA512CryptoServiceProvider();
            byte[] h512 = SHA512.ComputeHash(buffer);

            result = BitConverter.ToString(h512).Replace("-", string.Empty);

            return result.ToLower();
        }
    }
}
